<?php
	App::import("Model","Import.AbstractImport");
	App::import("Model","Listing");
	class ListingImport extends AbstractImport
	{
		var $name = "ListingImport";
		var $categoryId = null;
		function getImporterModel()
		{
			return cri("Listing");
		}
		
		function afterInitialize()
		{
			parent::afterInitialize();
		}
		function setImporFieldProperty()
		{
			$categoriesList = cri("ListCategory")->getCategoryTreeList();
			$this->setFieldProperties("list_category_id", array('label'=>__("Category"),"group"=>array("import"),"options"=>$categoriesList,'validate' => array('rule'=>
			array("inList",array_keys($categoriesList)),'message'=>__("Please select a valid category."),'required'=>true,'allowEmpty'=>false),'empty'=>__("-Select-")));
			$usersList = cri("Users.User")->find("list",array("fields"=>array("id","username")));
			$this->setFieldProperties("user_id", array('label'=>__("User"),"group"=>array("import"),"options"=>$usersList,'validate' => array('rule'=>
			array("inList",array_keys($usersList)),'message'=>__("Please select a valid user."),'required'=>true,'allowEmpty'=>false),'empty'=>__("-Select-")));
			$this->setFieldProperties('listing_status',array("label" => __("Status of imported listings"),'options'=>array(Listing::UNPUBLISH => __("Unpublish"),Listing::PUBLISH => __("Publish")),'empty'=>__("-Select-"),"group"=>array("import")) );
			$this->addFieldPropertiesValidationRule(array('user_id','listing_status','list_category_id'),true);
		}
		
		function setImportCategory($categoryId)
		{
			$this->categoryId = $categoryId;
			$this->getImporterModel()->setCategory($categoryId);
		}
		
		function getImportFields()
		{
			$fields =  $this->getImporterModel()->getFields("group","add");
			$fields = array_diff($fields,array("status"));
			//allow only if fopen is allowed over http;
			if($this->allowRemoteUrl())
				$fields[] = 'image';
			return $fields;
		}
		function allowRemoteUrl()
		{
			$ret = false;
			if(function_exists('ini_get') && ini_get('allow_url_fopen'))
			{
				$ret = true;
			}
			return $ret;
		}
		function getImportRequiredFields()
		{
			$fields = $this->getImporterModel()->getFields("required","1");
			$fields = am($fields,array("title"));
			return $fields;
		}
		
		function saveToImporterModel($data)
		{
			Configure::write("ListingConfig.enable_add_listing_admin_alert",false);
			$data['list_category_id'] = $this->categoryId;
			$image = null;
			if(isset($data['image']))
			{
				$image = $data['image'];
				if(!$this->allowRemoteUrl())
				{
					$image = null;
				}
				unset($data['image']);
			}
			$save = parent::saveToImporterModel($data);
			if($save === true)
			{
				if(!isset($this->ListingAsset) || !is_object($this->ListingAsset))
				{
					$this->ListingAsset = cri('ListingAsset');
				}
				$listingId = $this->getImporterModel()->id;
				$image = trim($image);
				if($listingId && $image && preg_match('/^http(s)?/', $image))
				{
					$exts = 	array("jpg",'bmp',"gif","png","jpeg");
					$ext = array_pop(explode('.',$image));
					$ok = true;
					if(!in_array(low($ext),$exts))
					{
						if(function_exists('get_headers'))
						{
							$headers = get_headers($image);
							if(isset($headers[0]) && strpos($headers[0],'200') !== false)
							{
								$ext  = @array_pop(explode("/",$headers['Content-Type']));
							}else
								{
									$ok = false;
								}
						}
						if(!in_array($ext,$exts))
							$ext = "jpg";
					}
					$ext = low($ext);
					$filename = 'listing_'.$listingId.'_'.time().'.'.$ext;
					$filePath = WWW_ROOT.'uploads'.DS.'listing_assets'.DS.$filename;
					$data = array('listing_id'=>$listingId,'name'=>$filename,'is_default'=>1,'user_id'=>$data['user_id'],'status'=>ListingAsset::PUBLISHED);
					if($ok)
					{
						
						$this->ListingAsset->create();
						if($this->ListingAsset->save(array($this->ListingAsset->alias => $data),array("validate"=>false,'callbacks'=>false)))
						{
							copy($image,$filePath);
						}
					}
				}
			}
			return $save;
		}
		function getImportFieldsAsOtpions()
		{
			$options = parent::getImportFieldsAsOtpions();
			if($this->allowRemoteUrl())
				$options['image'] = "URL of image";
			return $options;
		}
        protected function setFieldData($field,$value)
		{
			$value = parent::setFieldData($field, $value);
            $fieldType = $this->getImporterModel()->getFieldProperty($field,"type");
            if($fieldType == "countrySuggestor")
            {
              $countries = Utility::getCountries();
              $value = array_search($value, $countries);
            }
            return $value;
		}
	}